package ServiceThread;

import java.util.*;

import DataCenter.ConfigAccessor;
import Service.ServiceThread;
import ServiceProvider.BroadcastSender;

public class BroadcastThread extends ServiceThread {
	
	private BroadcastSender broadcastSender;
	
	private Scanner input = new Scanner(System.in);
	
	private static String TAG;
	private static String INPUTHINT;
	
	private boolean ifStopThread = true;
	
	public BroadcastThread() {
		
		INPUTHINT = "Please enter the content of Broadcast:(Exit with exit)";
		TAG = "Broadcast has been exited.";
		
		Map<String, String> broadcastConfig = ConfigAccessor.sharedInstance().getBroadcastConfig();
		String broadcastGroup = broadcastConfig.get("broadcastGroup");
		String port = broadcastConfig.get("port");
		this.broadcastSender = new BroadcastSender(broadcastGroup, port);
	}
	
	@Override
	public void run() {
		while (ifStopThread) {
			System.out.println(INPUTHINT);
			String message = input.nextLine();
			
			if (message.equals("Exit"))
				stopSelfThreadAndAwakenWaitingThread();
			else
				broadcastSender.broadcast("CHAT>Talon:" + message);
		}
		
		System.out.println(TAG);
	}

	private void stopSelfThreadAndAwakenWaitingThread() {
		ifStopThread = false;
		synchronized (this) {
			this.notify();
		}
	}
}
